﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using SCRUM.Core.Configuration;
using SCRUM.Core.DAO;
using SCRUM.Core.BusinessObjects;
using System.Collections.Generic;
using System.Web;

/// <summary>
/// Class that represents column in tab
/// </summary>
public partial class Column : System.Web.UI.UserControl
{
    /// <summary>
    /// Max number of columns in tab
    /// </summary>
    public static int maxColumns = 3;

    /// <summary>
    /// Width of column
    /// </summary>
    public decimal columnWidth { get; set; }

    /// <summary>
    /// Column representation in domain
    /// </summary>
    public WidgetColumn column { get; set; }

    /// <summary>
    /// Number fo widgets inserted to column
    /// </summary>
    public int insertedWidgetsCount { get; set; }

    /// <summary>
    /// Tab that column belongs to
    /// </summary>
    public WidgetTab parent { get; set; }

    /// <summary>
    /// Index of tab that column belongs to
    /// </summary>
    public int tabIndex { get; set; }

    /// <summary>
    /// All types of widgets available to insert into column
    /// </summary>
    private IList<WidgetType> widgetTypes { get; set; }

    /// <summary>
    /// Do not use this without parameters set
    /// </summary>
    public Column()
    {
        insertedWidgetsCount = 0;
    }

    /// <summary>
    /// Adds widgets to column according to settings
    /// </summary>
    public void createColumn()
    {
        Widgets.Style.Add(HtmlTextWriterStyle.Width, String.Format("{0}%", columnWidth.ToString()));
        Widgets.Style.Add("min-width", String.Format("{0}px", ConfigManager.CurrentConfig.Widgets.MinimalWidth));
        Widgets.Attributes.Add("class", "tabColumn");

        foreach (Widget widget in column.Widgets)
        {
            WidgetBase widgetToInsert = LoadControl(String.Format("~/Widgets/{0}/widget.ascx", widget.Type)) as WidgetBase;
            WidgetContainer container = LoadControl("~/User Controls/Dashboard/WidgetContainer.ascx") as WidgetContainer;
            widgetToInsert.ID = widget.ID;
            widgetToInsert.TypeID = widget.TypeID;
            container.Widget = widgetToInsert;

            Widgets.Controls.Add(container);

            insertedWidgetsCount++;
        }
        if (insertedWidgetsCount == 0)
        {
            Panel p = new Panel();
            p.CssClass = "EmptyTabMessage";
            Literal text = new Literal();
            text.Text = (string)GetLocalResourceObject("EmptyTabMessage");
            p.HorizontalAlign = HorizontalAlign.Center;
            p.Controls.Add(text);
            Widgets.Controls.Add(p);
        }

        //initialize settings for column
        initializeEditTab();
    }

    /// <summary>
    /// Set all data and visibility to edit part of column
    /// </summary>
    public void initializeEditTab()
    {

        AllWidgets.DataTextField = "TypeToDisplay";
        AllWidgets.DataValueField = "ID";
        
            AllWidgets.DataSource = column.Widgets;
        AllWidgets.DataBind();
        if (AllWidgets.Items.Count > 0)
        {
            AvailableWidgets.SelectedIndex = 0;
        }

        // Load all widget types available for current user
        widgetTypes = DAOWidgetType.GetAllAvailableWidgetTypes();
        AvailableWidgets.DataTextField = "Name";
        AvailableWidgets.DataValueField = "ID";
        AvailableWidgets.AutoPostBack = true;
        AvailableWidgets.DataSource = widgetTypes;
        AvailableWidgets.DataBind();
        if (AvailableWidgets.Items.Count > 0)
        {
            AvailableWidgets.SelectedIndex = 0;
        }
        AddAfter.Visible = parent.Columns.Count < 3;
        AddBefore.Visible = parent.Columns.Count < 3;
        Up.Enabled = column.Widgets.Count > 1;
        Down.Enabled = column.Widgets.Count > 1;
        Delete.Enabled = column.Widgets.Count != 0;
        if (column.Widgets.Count == 0)
        {
            Widget w = new Widget(0, "NoWidgetPresent", 0, 0);
            List<Widget> data = new List<Widget>();
            data.Add(w);
            AllWidgets.DataSource = data;
            AllWidgets.DataBind();
        }
    }

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        this.ButtonDeleteActiveTab.Enabled = true;
        this.Widgets.Attributes["onmouseover"] = String.Format("showEditOptions('{0}', true)", this.columnOperationDiv.ClientID);
        this.Widgets.Attributes["onmouseout"] = String.Format("showEditOptions('{0}', false)", this.columnOperationDiv.ClientID);
    }

    /// <summary>
    /// Sets visibility of edit part of column
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void edit_Click(object sender, EventArgs e)
    {
        PanelTabOptions.Visible = !PanelTabOptions.Visible;
    }

    /// <summary>
    /// User wants to add new widget after actual column.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void AddAfter_Click(object sender, EventArgs e)
    {
        if (parent.Columns.Count < maxColumns)
        {
            int order = parent.Columns.IndexOf(column);
            WidgetColumn newColumn = new WidgetColumn(0, order, 22);
            DAOWidgetColumn.AddColumn(newColumn, parent, false);
            Response.Redirect("~/Default.aspx?tabId=" + tabIndex.ToString());
        }
    }

    /// <summary>
    /// User wants to add new widget before actual column
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void AddBefore_Click(object sender, EventArgs e)
    {
        if (parent.Columns.Count < maxColumns)
        {
            int order = parent.Columns.IndexOf(column);
            WidgetColumn newColumn = new WidgetColumn(0, order, 22);
            DAOWidgetColumn.AddColumn(newColumn, parent, true);
            Response.Redirect("~/Default.aspx?tabId=" + tabIndex.ToString());
        }
    }
    
    /// <summary>
    /// User wants to delete column
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ButtonDeleteActiveTab_Click(object sender, EventArgs e)
    {
        DAOWidgetColumn.DeleteColumn(column);
        Response.Redirect("~/Default.aspx?tabId=" + tabIndex.ToString());
    }

    /// <summary>
    /// Gets selected widget type from first list and adds it on 0 position to column
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Parameters</param>
    protected void ButtonAddNewWidget_Click(object sender, EventArgs e)
    {
        int widgetTypeID = System.Convert.ToInt32(AvailableWidgets.SelectedValue);
        int order = 0;
        DAOWidget.CreateNewWidget(widgetTypeID, order, column.ID);
        Response.Redirect("~/Default.aspx?tabId=" + tabIndex.ToString());
    }

    /// <summary>
    /// Deletes selected widget from column
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Parameter</param>
    protected void Delete_Click(object sender, EventArgs e)
    {
        if (AllWidgets.SelectedIndex != -1)
        {
            DAOWidget.DeleteWidget(DAOWidget.GetWidgetByID(System.Convert.ToInt32(AllWidgets.SelectedValue)));
            Response.Redirect("~/Default.aspx?tabId=" + tabIndex.ToString());
        }
    }

    /// <summary>
    /// Moves widget one level up in column
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Parameter</param>
    protected void Up_Click(object sender, EventArgs e)
    {
        if (AllWidgets.SelectedIndex != -1)
        {
            if (AllWidgets.SelectedIndex != 0)
            {
                Widget widget = new Widget();
                widget.Type = AllWidgets.SelectedItem.Text;
                widget.ID = System.Convert.ToInt32(AllWidgets.SelectedValue);
                widget.Order = System.Convert.ToInt32(AllWidgets.SelectedIndex);
                DAOWidget.ChangeWidgetOrder(widget, true);
                Response.Redirect("~/Default.aspx?tabId=" + tabIndex.ToString());
            }
        }
    }

    /// <summary>
    /// Moves widget one level down in column
    /// </summary>
    /// <param name="sender">Sender</param>
    /// <param name="e">Parameter</param>
    protected void Down_Click(object sender, EventArgs e)
    {
        if (AllWidgets.SelectedIndex != -1)
        {
            if (AllWidgets.SelectedIndex != (AllWidgets.DataSource as IList<Widget>).Count - 1)
            {
                Widget widget = new Widget();
                widget.ID = System.Convert.ToInt32(AllWidgets.SelectedValue);
                DAOWidget.ChangeWidgetOrder(widget, false);
                Response.Redirect("~/Default.aspx?tabId=" + tabIndex.ToString());
            }
        }
    }
    /// <summary>
    /// Handles the SelectedIndexChanged event of the AvailableWidgets control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void AvailableWidgets_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.LiteralDescription.Text = widgetTypes[AvailableWidgets.SelectedIndex].Description.Replace("\n","<br />");
	}

	/// <summary>
	/// Raises the <see cref="E:System.Web.UI.Control.PreRender"/> event.
	/// </summary>
	/// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
	protected override void OnPreRender(EventArgs e)
	{
		base.OnPreRender(e);
		if (column.Widgets.Count == 0)
		{
			this.PanelTabOptions.Visible = true;
		}
	}
}
